package com.steak.system.controller.security;

import com.auth0.jwt.JWT;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.fdfs.ThumbImageConfig;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.steak.system.common.base.BaseController;
import com.steak.system.common.exception.BusinessException;
import com.steak.system.common.exception.EmBusinessError;
import com.steak.system.common.resultType.Result;
import com.steak.system.pojo.dataobject.UserDO;
import com.steak.system.pojo.dto.UserDTO;
import com.steak.system.pojo.vo.UserInfoVO;
import com.steak.system.pojo.vo.UserLoginVO;
import com.steak.system.service.security.UserService;
import com.steak.system.util.Base64Util;
import com.steak.system.util.ConvertUtils;
import com.steak.system.util.JwtUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.jms.Queue;
import javax.jms.Topic;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.UUID;


@RestController
public class LoginController extends BaseController{

    @Autowired
    private UserService userService;
    @Autowired
    private FastFileStorageClient storageClient;
    @Value("${imagePath}")
    private String serverPort;
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Autowired
    private Topic topic;
    /**
     * 用户登陆，生成token
     * @param userId
     * @param password
     * @return
     * @throws BusinessException
     */
    @PostMapping("login")
    public Result Login(@RequestParam("userId")String userId , @RequestParam("password")String password) throws BusinessException {
        UserDTO userInfo = userService.getUserInfo(userId);
        if (!userInfo.getPassword().equals(password)){
            throw new BusinessException(EmBusinessError.PASSWORD_ERROR);
        }
        String token = JwtUtil.createJWT(700000,userInfo);
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setToken(token);
        return Result.create(userLoginVO);
    }

    /**
     * 获取用户信息,获取用户信息带上token
     * @param request
     * @return
     * @throws BusinessException
     */
    @GetMapping("userInfo")
    public Result getUserInfo(HttpServletRequest request) throws BusinessException {
        String token = request.getHeader("TOKEN");
        String userId = JWT.decode(token).getClaim("userId").asString();
        UserDTO userDTO = userService.getUserInfo(userId);
        if (JwtUtil.checkJWT(token,userDTO)){
            UserInfoVO userInfoVO = (UserInfoVO) ConvertUtils.DtoToVo(userDTO,new UserInfoVO());
            return Result.create(userInfoVO);
        }else {
            return Result.create("overdue");
        }
    }

    /**
     * 注册
     * @param userId
     * @param username
     * @param password
     * @param sex
     * @return
     */
    @PostMapping("register")
    public Result register(@RequestParam("userId")String userId, @RequestParam("username")String username, @RequestParam("password")String password,
                           @RequestParam("sex")Integer sex, @RequestParam("tel")String tel,
                           @RequestParam("imgBase64")String imgBase64,@RequestParam("studentEmail")String studentEmail) throws BusinessException, FileNotFoundException {
        imgBase64 = imgBase64.replace("data:image/jpeg;base64,","");
        File file = Base64Util.base64ConvertFile(imgBase64);
        StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(new FileInputStream(file),file.length(),"jpg",null);

        if (userId.isEmpty() || username.isEmpty() || password.isEmpty() || sex == 0 || tel.isEmpty()){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        String photoURL = serverPort+storePath.getFullPath();
        UserDO userDO = new UserDO();
        userDO.setUserId(userId);
        userDO.setUserName(username);
        userDO.setPassword(password);
        userDO.setSex(sex);
        userDO.setTel(tel);
        userDO.setEmail(studentEmail);
        userDO.setPhoto(photoURL);
        userDO.setRoleId("4");
        jmsMessagingTemplate.convertAndSend(topic,userDO);
        return Result.create(20000);
    }

    /**
     * 登出
     * @return
     */
    @GetMapping("logout")
    public Result logout(){
        return Result.create("success");
    }

}
